package net.adst.ui.mainframe.toppanel;

import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JTextFieldDateEditor;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.util.DataManager;
import net.adst.util.GBC;
import net.adst.util.MyUtils;
import sun.net.ResourceManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class PeriodChooserArea extends JPanel {

    private final JDateChooser dateFrom;
    private final JDateChooser dateTo;
    private final JButton backButtonFrom;
    private final JButton nextButtonFrom;
    private final JButton backButtonTo;
    private final JButton nextButtonTo;
    private JLabel startDateLabel;
    private JLabel endDateLabel;
    private JCheckBox allTime;

    public PeriodChooserArea() {
        setLayout(new GridBagLayout());
        ImageIcon backIcon = new ImageIcon(ResourceManager.class.getResource("/images/back.png"));
        ImageIcon nextIcon = new ImageIcon(ResourceManager.class.getResource("/images/next.png"));
        backButtonFrom = new JButton(backIcon);
        dateFrom = new JDateChooser();
        nextButtonFrom = new JButton(nextIcon);
        backButtonTo = new JButton(backIcon);
        dateTo = new JDateChooser();
        nextButtonTo = new JButton(nextIcon);

        addPeriodChooser();
        setStartDates();
        addCommonFunctionality();
    }

    /**
     * Adds "lock" and "recent week" buttons, "from" and "to" dates
     */
    private void addPeriodChooser() {
        startDateLabel = new JLabel("Выберете начальную дату:");
//        startDateLabel.setMaximumSize(new Dimension(95, 20));
//        startDateLabel.setPreferredSize(new Dimension(95, 20));
//        startDateLabel.setMinimumSize(new Dimension(95, 20));
        add(startDateLabel, new GBC(0, 0, 3, 1).setInsets(0, 0, 5, 5).setAnchor(GBC.WEST));
        backButtonFrom.setMargin(new Insets(3, 3, 3, 3));
        backButtonFrom.setFocusPainted(false);
        add(backButtonFrom, new GBC(0, 1).setInsets(0, 0, 0, 0).setAnchor(GBC.WEST));

        SimpleDateFormat fmt = (SimpleDateFormat) DateFormat.getDateInstance(Constants.calendarDateFormat);
        dateFrom.setCalendar(Calendar.getInstance());
        dateFrom.setDateFormatString(fmt.toPattern());
        dateFrom.getJCalendar().setWeekOfYearVisible(false);
        dateFrom.setMaximumSize(new Dimension(90, 18));
        dateFrom.setPreferredSize(new Dimension(90, 18));
        dateFrom.setMinimumSize(new Dimension(90, 18));

        add(dateFrom, new GBC(1, 1).setInsets(0, 0, 0, 0).setAnchor(GBC.WEST).setIpad(15, 0)); // 65 was

        nextButtonFrom.setMargin(new Insets(3, 3, 3, 3));
        nextButtonFrom.setFocusPainted(false);
        add(nextButtonFrom, new GBC(2, 1).setInsets(0, 0, 0, 0).setAnchor(GBC.WEST));

        endDateLabel = new JLabel("Выберете конечую дату:");
        add(endDateLabel, new GBC(0, 2, 3, 1).setInsets(10, 0, 5, 5).setAnchor(GBC.WEST));

        backButtonTo.setMargin(new Insets(3, 3, 3, 3));
        backButtonTo.setFocusPainted(false);
        add(backButtonTo, new GBC(0, 3).setInsets(0, 0, 0, 0));

        dateTo.setCalendar(Calendar.getInstance());
        dateTo.setDateFormatString(fmt.toPattern());
        dateTo.getJCalendar().setWeekOfYearVisible(false);
        dateTo.setMaximumSize(new Dimension(90, 18));
        dateTo.setPreferredSize(new Dimension(90, 18));
        dateTo.setMinimumSize(new Dimension(90, 18));

        add(dateTo, new GBC(1, 3).setInsets(0, 0, 0, 0).setIpad(15, 0)); // 65 was
        nextButtonTo.setMargin(new Insets(3, 3, 3, 3));
        nextButtonTo.setFocusPainted(false);
        add(nextButtonTo, new GBC(2, 3).setInsets(0, -25, 0, 0));

        Calendar minDate = Calendar.getInstance();
        minDate.set(2000, 1, 1, 0, 0, 0);
        dateFrom.setMinSelectableDate(minDate.getTime());
        dateTo.setMinSelectableDate(minDate.getTime());

        allTime = new JCheckBox("за все время существования");
        allTime.setFocusPainted(false);
        DataManager.setObject(VariableNames.TOP_PANEL_ALL_TIME, allTime.isSelected());
        add(allTime, new GBC(0, 4, 3, 1).setInsets(0, 0, 0, 0));

        ((JTextFieldDateEditor) dateFrom.getDateEditor()).setEditable(false);
        ((JTextFieldDateEditor) dateTo.getDateEditor()).setEditable(false);
    }

    /**
     * Adds common functionality for reports and favourite tab
     */
    private void addCommonFunctionality() {


        backButtonFrom.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //ORS-65 fix
                if ((dateFrom.getDate() == null)) {
                    return;
                }
                Calendar dtFr = dateFrom.getCalendar();
                dtFr.add(Calendar.DATE, -1);
                dateFrom.setCalendar(dtFr);
                checkValid();
            }
        });

        nextButtonFrom.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //ORS-65 fix
                if ((dateFrom.getDate() == null)) {
                    return;
                }
                Calendar dtFr = dateFrom.getCalendar();
                dtFr.add(Calendar.DATE, 1);
                dateFrom.setCalendar(dtFr);
                checkValid();
            }
        });

        nextButtonTo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //ORS-65 fix
                if ((dateTo.getDate() == null)) {
                    return;
                }
                Calendar dtFr = dateTo.getCalendar();
                dtFr.add(Calendar.DATE, 1);
                dateTo.setCalendar(dtFr);
                checkValid();
            }
        });

        backButtonTo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //ORS-65 fix
                if ((dateTo.getDate() == null)) {
                    return;
                }
                Calendar dtFr = dateTo.getCalendar();
                dtFr.add(Calendar.DATE, -1);
                dateTo.setCalendar(dtFr);
                checkValid();
            }
        });
        PropertyChangeListener datesListener = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                checkValid();
            }
        };
        dateFrom.addPropertyChangeListener(datesListener);
        dateTo.addPropertyChangeListener(datesListener);

        allTime.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DataManager.setObject(VariableNames.TOP_PANEL_ALL_TIME, allTime.isSelected());
                if (allTime.isSelected()) {
                    dateFrom.setEnabled(false);
                    backButtonFrom.setEnabled(false);
                    dateTo.setEnabled(false);
                    nextButtonTo.setEnabled(false);
                    backButtonTo.setEnabled(false);
                    nextButtonFrom.setEnabled(false);
                } else {
                    backButtonFrom.setEnabled(true);
                    dateFrom.setEnabled(true);
                    nextButtonFrom.setEnabled(true);
                    backButtonTo.setEnabled(true);
                    dateTo.setEnabled(true);
                    nextButtonTo.setEnabled(true);
                }
            }
        });
    }

    public void setStartDates() {
        Calendar dtFrom = Calendar.getInstance();
        Calendar dtTo = Calendar.getInstance();
        dtFrom.set(Calendar.DAY_OF_WEEK, dtFrom.getFirstDayOfWeek());
        dateFrom.setDate(dtFrom.getTime());
        dateTo.setDate(dtTo.getTime());
        DataManager.setObject(VariableNames.CALENDAR_DATE_FROM, dateFrom);
        DataManager.setObject(VariableNames.CALENDAR_DATE_TO, dateTo);
        if (DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL) != null && DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL) != null) {
            ((JLabel) DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL)).setVisible(false);
            ((JLabel) DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL)).setVisible(true);
        }
    }

    private void checkValid() {
        if (MyUtils.compareDate(dateTo.getDate(), dateFrom.getDate()) && MyUtils.compareDate(dateFrom.getDate(), dateTo.getDate())) {
            nextButtonFrom.setEnabled(false);
            backButtonTo.setEnabled(false);
            ((JTextFieldDateEditor) dateTo.getDateEditor()).setForeground(Color.BLACK);
            ((JTextFieldDateEditor) dateFrom.getDateEditor()).setForeground(Color.BLACK);
            if (DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL) != null && DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL) != null) {
                ((JLabel) DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL)).setVisible(true);
                ((JLabel) DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL)).setVisible(true);
            }
        } else if (MyUtils.compareDate(dateFrom.getDate(), dateTo.getDate())) {
            ((JTextFieldDateEditor) dateTo.getDateEditor()).setForeground(Color.RED);
            ((JTextFieldDateEditor) dateFrom.getDateEditor()).setForeground(Color.RED);
            nextButtonFrom.setEnabled(false);
            backButtonTo.setEnabled(false);
        } else {
            ((JTextFieldDateEditor) dateTo.getDateEditor()).setForeground(Color.BLACK);
            ((JTextFieldDateEditor) dateFrom.getDateEditor()).setForeground(Color.BLACK);
            if (DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL) != null && DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL) != null) {
                ((JLabel) DataManager.getObject(VariableNames.UI_NAEM_NEED_UPDATE_LABEL)).setVisible(true);
                ((JLabel) DataManager.getObject(VariableNames.UI_OUR_NEED_UPDATE_LABEL)).setVisible(true);
            }
            nextButtonFrom.setEnabled(true);
            backButtonTo.setEnabled(true);
        }
    }
}
